package com.insurance.Interceptor;

import com.insurance.common.ResultData;
import com.insurance.pojo.JwtResult;
import com.insurance.utils.JwtUtil;
import com.insurance.utils.WriterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/10/21 19:07
 * Description:
 * Version: V1.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    ResultData resultData;

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object o) throws Exception {
        //获取头字段token的值
        String token=request.getHeader("token");
        //验证token
        JwtResult jwtResult=JwtUtil.validateJwt(token);
        if (jwtResult.isSuccess()){
            String token1= JwtUtil.createJwt(UUID.randomUUID().toString(),"zhuxiong",JwtUtil.generalSubject(resultData.getData()),JwtUtil.TTMILLS);
            resultData.setToken(token1);
            System.out.println("验证通过");
            return true;
        }else {
            if (jwtResult.getErrCode() == JwtUtil.JWT_ERRCODE_EXPIRE){
                resultData.setCode(500);
                resultData.setMsg("登录身份过期，请重新登录");
                resultData.setData(jwtResult);
            }else if (jwtResult.getErrCode() == JwtUtil.JWT_ERRCODE_FAIL){
                resultData.setCode(500);
                resultData.setMsg("请先登录");
                resultData.setData(jwtResult);
            }
            WriterUtil.getWriter(response,resultData);
            return false;
        }
    }

    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
